package com.sgb.kjwl.view.ui.activity.self.company

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.SpanUtils
import com.google.android.material.tabs.TabLayout
import com.sgb.capital.callback.Constants
import com.sgb.capital.callback.ZMessageEvent
import com.sgb.capital.model.Bean
import com.sgb.capital.model.CommodityBean
import com.sgb.capital.utils.Utils
import com.sgb.capital.view.ui.fragment.CommodityFragment
import com.sgb.capital.view.ui.fragment.CommodityListFragment
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.BR
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityQuotationBinding
import com.sgb.kjwl.view.ui.fragment.self.company.InviteFragment
import com.sgb.kjwl.viewmodel.self.company.QuotationViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * 报价列表
 */
class QuotationActivity : AppActivity() {

    private lateinit var mBinding: ActivityQuotationBinding
    private lateinit var mViewModel: QuotationViewModel
    private lateinit var mAdapter: QuotationPageAdapter
    private val mTitles = arrayOf("收到的报价", "发起的报价")
    private val mSecondTitles = arrayOf("招采", "集采", "商品", "租赁")
    private var fragmentList = ArrayList<Fragment>()
    private var mBean: Bean? = null
    private var mPosition: Int = 0

    companion object {
        fun launch(context: Context) {
            val intent = Intent(context, QuotationActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView() {
        super.initView()
        EventBus.getDefault().register(this)
        mBean = Bean()
        mViewModel = QuotationViewModel()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_quotation)
        mBinding.setVariable(BR.mmodel, mViewModel)
        mBinding.lifecycleOwner = this

        mBinding.include.ivBack.setOnClickListener { finish() }
        mBinding.include.titleView.text = "报价列表"
        renderFirstTab()
        renderSecondTab()
    }

    private fun renderFirstTab() {
        for (item in mTitles) {
            val tab: TabLayout.Tab = mBinding.titleTabView.newTab()
            tab.text = item
            mBinding.titleTabView.addTab(tab)
        }
        mBinding.titleTabView.getTabAt(0)!!.select()
        mBinding.titleTabView.tabMode = TabLayout.MODE_FIXED
        mBinding.titleTabView.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {
                mPosition = tab!!.position
                mBean!!.posFirst = tab!!.position
                Utils.sendMsg(Constants.EVENT_REFRESH_COMMODITY, mBean)
                refreshInquiryFragment(mBinding.titleSelectedTabView.selectedTabPosition)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })
    }

    private fun renderSecondTab() {
        fragmentList.clear()
        for (item in mSecondTitles) {
            if (item.contains("商品")) fragmentList.add(CommodityFragment.newInstance("报价"))
            else fragmentList.add(InviteFragment.newInstance(item))
        }
        mAdapter = QuotationPageAdapter(supportFragmentManager, fragmentList, mSecondTitles)
        mBinding.titleViewPager.adapter = mAdapter
        mBinding.titleViewPager.offscreenPageLimit = fragmentList.size
        mBinding.titleSelectedTabView.setupWithViewPager(mBinding.titleViewPager)
        mBinding.titleViewPager.currentItem = 0
        mBinding.titleViewPager.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                refreshInquiryFragment(position)
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        mBinding.titleSelectedTabView.addOnTabSelectedListener(object :
                TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val textView = tab?.view?.getChildAt(1) as TextView
                textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                mBean!!.posSecond = tab!!.position
                if (mBean!!.posSecond==2){
                    Utils.sendMsg(Constants.EVENT_REFRESH_COMMODITY, mBean)
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                val textView = tab?.view?.getChildAt(1) as TextView
                textView.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })
    }

    /**
     *设置TabItem右上角的总数量
     * @param tabIndex 要设置数量显示的TabItem的index,从0开始
     * @param count 总计的数量
     */
    fun updateTabViewCount(tabIndex: Int, count: Int) {
        if (tabIndex < 0 || tabIndex >= mBinding.titleSelectedTabView.tabCount) {
            throw IndexOutOfBoundsException("input tabIndex is outside the CharSequence")
        } else {
            val totalName = mBinding.titleSelectedTabView.getTabAt(tabIndex)?.view?.getChildAt(1) as TextView
            val tabName: String = mSecondTitles[tabIndex]
            SpanUtils.with(totalName)
                    .append(tabName)
                    .setFontSize(14, true)
                    .appendSpace(0)
                    .append(if (count == 0) "" else "(" + String.format("%s", if (count >= 100) String.format("%s+", 99) else count.toString()) + ")")
                    .setFontSize(12, true)
                    .create()
        }
    }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    fun refreshInquiryFragment(position: Int) {
        var fragment = fragmentList[position]!!
        if (fragment is InviteFragment) {
            val onLazyLoad = fragment
            onLazyLoad.onLazyLoad()
        }
    }

    class QuotationPageAdapter(
            fm: FragmentManager,
            fragmentList: ArrayList<Fragment>,
            mSecondTitles: Array<String>
    ) : FragmentPagerAdapter(fm) {
        private var fragmentList: ArrayList<Fragment>? = null
        private var mSecondTitles: Array<String>? = null

        init {
            this.fragmentList = fragmentList
            this.mSecondTitles = mSecondTitles
        }

        override fun getCount(): Int {
            return if (fragmentList == null) 0 else fragmentList!!.size
        }

        override fun getItem(position: Int): Fragment {
            return fragmentList!![position]
        }

        override fun getPageTitle(position: Int): CharSequence {
            return mSecondTitles!![position]
        }
    }


    @Subscribe
    fun getCode(event: ZMessageEvent) {
        when (event.code) {
            Constants.EVENT_REFRESH_COUNT -> {
                updateTabViewCount(2, event.data as Int)
            }
            Constants.EVENT_CLICK -> {
                val listDTO = event.data as CommodityBean.ListDTO
                mViewModel.getDataInfo(this, listDTO?.no, mPosition)
            }
        }
    }

}